<?php

namespace App\Command;

use App\Model\Device;
use App\Services\Iot\IotService;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Workerman\Mqtt\Client;
use Workerman\Worker;

/**
 * @Command
 */
class SubscribeIot extends HyperfCommand
{
    public function configure()
    {
        $this->setName('subscribe:iot')
            ->setDescription('Subscribe to IoT actions')
            ->addArgument('action', InputArgument::REQUIRED, 'Action to subscribe')
            ->addOption('d', null, InputOption::VALUE_NONE, 'Enable debugging');
    }

    public function handle()
    {
        $action = $this->input->getArgument('action');
        $debug = $this->input->getOption('d');
        if(!$debug){
            $debug = '';
        }
        global $argv;
        $argv[0] = 'wk';
        $argv[1] = $action;
        $argv[2] = $debug;
        $worker = new Worker();
        $worker->onWorkerStart = function(){
            $mqtt = IotService::getClient();

            $mqtt->onConnect = function(Client $mqtt) {
                $mqtt->subscribe([
                    '/v1/device/+/rx' => 0
                ]);
            };
            $mqtt->onMessage = function($topic, $content, $mqtt){
//                $content = ur;
                //logger('iot message topic ' . $topic);
                $strLen = strlen($content);
                $messageResult = [];
                $messageResultLog = [];
                for ($i = 0; $i < $strLen; $i ++) {

                    # code..
                    $item = ord(substr($content, $i, 1));
                    $messageResult[] = $item;
                    //转为16进制记录日志 方便使用
                    $messageResultLog[] = dechex($item);
                }
                //logger('iot message content array ', $messageResultLog);

                preg_match('/(device\/)(.*)(?)(\/rx)/', $topic, $result);
                $imei = $result[2];
                $device = Device::where('iot_sn', $imei)->first();

                if(!$device) {
                    logger('iot message error ' . $imei . ' not found');
                    return;
                }

                $device->iotEventHandle($messageResult, $mqtt);

            };
            $mqtt->connect();
        };
        Worker::runAll();
    }
}
